{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# survo_puzzle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/survo_puzzle.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/survo_puzzle.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Survo puzzle Google CP Solver.\n",
    "\n",
    "  http://en.wikipedia.org/wiki/Survo_Puzzle\n",
    "  '''\n",
    "  Survo puzzle is a kind of logic puzzle presented (in April 2006) and studied\n",
    "  by Seppo Mustonen. The name of the puzzle is associated to Mustonen's\n",
    "  Survo system which is a general environment for statistical computing and\n",
    "  related areas.\n",
    "\n",
    "  In a Survo puzzle the task is to fill an m * n table by integers 1,2,...,m*n\n",
    "  so\n",
    "  that each of these numbers appears only once and their row and column sums are\n",
    "  equal to integers given on the bottom and the right side of the table.\n",
    "  Often some of the integers are given readily in the table in order to\n",
    "  guarantee uniqueness of the solution and/or for making the task easier.\n",
    "  '''\n",
    "\n",
    "  See also\n",
    "  http://www.survo.fi/english/index.html\n",
    "  http://www.survo.fi/puzzles/index.html\n",
    "\n",
    "  References:\n",
    "  Mustonen, S. (2006b). \"On certain cross sum puzzles\"\n",
    "  http://www.survo.fi/papers/puzzles.pdf\n",
    "  Mustonen, S. (2007b). \"Enumeration of uniquely solvable open Survo puzzles.\"\n",
    "  http://www.survo.fi/papers/enum_survo_puzzles.pdf\n",
    "  Kimmo Vehkalahti: \"Some comments on magic squares and Survo puzzles\"\n",
    "  http://www.helsinki.fi/~kvehkala/Kimmo_Vehkalahti_Windsor.pdf\n",
    "  R code: http://koti.mbnet.fi/tuimala/tiedostot/survo.R\n",
    "\n",
    "  Compare with the following models:\n",
    "  * Choco   : http://www.hakank.org/choco/SurvoPuzzle.java\n",
    "  * Comet   : http://www.hakank.org/comet/survo_puzzle.co\n",
    "  * ECLiPSE : http://www.hakank.org/eclipse/survo_puzzle.ecl\n",
    "  * Gecode  : http://www.hakank.org/gecode/survo_puzzle.cpp\n",
    "  * Gecode/R: http://www.hakank.org/gecode_r/survo_puzzle.rb\n",
    "  * JaCoP   : http://www.hakank.org/JaCoP/SurvoPuzzle.java\n",
    "  * MiniZinc: http://www.hakank.org/minizinc/survo_puzzle.mzn\n",
    "  * Tailor/Essence': http://www.hakank.org/tailor/survo_puzzle.eprime\n",
    "  * Zinc: http://www.hakank.org/minizinc/survo_puzzle.zinc\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def main(r=0, c=0, rowsums=[], colsums=[], game=[]):\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver(\"Survo puzzle\")\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  if r == 0:\n",
    "    r = 3\n",
    "    c = 4\n",
    "    rowsums = [30, 18, 30]\n",
    "    colsums = [27, 16, 10, 25]\n",
    "    game = [[0, 6, 0, 0], [8, 0, 0, 0], [0, 0, 3, 0]]\n",
    "\n",
    "  print(\"r:\", r, \"c:\", c)\n",
    "\n",
    "  # declare variables\n",
    "  x = {}\n",
    "  for i in range(r):\n",
    "    for j in range(c):\n",
    "      x[(i, j)] = solver.IntVar(1, r * c, \"x %i %i\" % (i, j))\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "\n",
    "  #\n",
    "  # set the clues\n",
    "  #\n",
    "  for i in range(r):\n",
    "    for j in range(c):\n",
    "      if game[i][j] > 0:\n",
    "        solver.Add(x[i, j] == game[i][j])\n",
    "\n",
    "  xflat = [x[(i, j)] for i in range(r) for j in range(c)]\n",
    "  solver.Add(solver.AllDifferent(xflat))\n",
    "  #\n",
    "  # calculate rowsums and colsums\n",
    "  #\n",
    "  for i in range(r):\n",
    "    solver.Add(rowsums[i] == solver.Sum([x[i, j] for j in range(c)]))\n",
    "\n",
    "  for j in range(c):\n",
    "    solver.Add(colsums[j] == solver.Sum([x[i, j] for i in range(r)]))\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  solution = solver.Assignment()\n",
    "  solution.Add([x[(i, j)] for i in range(r) for j in range(c)])\n",
    "\n",
    "  collector = solver.AllSolutionCollector(solution)\n",
    "  solver.Solve(\n",
    "      solver.Phase(xflat, solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE),\n",
    "      [collector])\n",
    "\n",
    "  num_solutions = collector.SolutionCount()\n",
    "  print(\"\\nnum_solutions: \", num_solutions)\n",
    "  if num_solutions > 0:\n",
    "    for s in range(num_solutions):\n",
    "      xval = [collector.Value(s, x[(i, j)]) for i in range(r) for j in range(c)]\n",
    "\n",
    "      for i in range(r):\n",
    "        for j in range(c):\n",
    "          print(\"%2i\" % (xval[i * c + j]), end=\" \")\n",
    "        print()\n",
    "      print()\n",
    "\n",
    "    print()\n",
    "    print(\"num_solutions:\", num_solutions)\n",
    "    print(\"failures:\", solver.Failures())\n",
    "    print(\"branches:\", solver.Branches())\n",
    "    print(\"WallTime:\", solver.WallTime())\n",
    "\n",
    "  else:\n",
    "    print(\"No solutions found\")\n",
    "\n",
    "\n",
    "#\n",
    "# Read a problem instance from a file\n",
    "#\n",
    "def read_problem(file):\n",
    "  f = open(file, \"r\")\n",
    "  r = int(f.readline())\n",
    "  c = int(f.readline())\n",
    "  rowsums = f.readline()\n",
    "  colsums = f.readline()\n",
    "  rowsums = [int(t) for t in (rowsums.rstrip()).split(\",\")]\n",
    "  colsums = [int(t) for t in (colsums.rstrip()).split(\",\")]\n",
    "  game = []\n",
    "  for i in range(r):\n",
    "    x = f.readline()\n",
    "    x = [int(t) for t in (x.rstrip()).split(\",\")]\n",
    "    row = [0] * c\n",
    "    for j in range(c):\n",
    "      row[j] = int(x[j])\n",
    "    game.append(row)\n",
    "  return [r, c, rowsums, colsums, game]\n",
    "\n",
    "\n",
    "if len(sys.argv) > 1:\n",
    "  file = sys.argv[1]\n",
    "  [r, c, rowsums, colsums, game] = read_problem(file)\n",
    "  main(r, c, rowsums, colsums, game)\n",
    "else:\n",
    "  main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
